<div class="full-screen">
  <header class="bg-red fixed" >
    <div class="a-bar">
      <a href="javascript:history.back()" class="a-back">
        <i class="arr left"></i>
        返回
      </a>

      <div class="a-right">
        <form class="a-search active" action="<{link app=b2c ctl=wap_search act=result}>" method="post" id="J_search_pt">
          <input class="a-search-ipt" type="text" name="search_keywords" value="" style="display: inline"/>
          <input class="a-search-btn" type="button" name="" value="" id="J_search" />
        </form>
      </div>
    </div>
  </header>
  <div class="pt-gallery">
    <div class="tab J-tab">
      <ul class="trigger-list fixed" style="top: .84rem;position: fixed">
        <li class="trigger act">
          默认
        </li>
        <li class="trigger price-seq">
          价格
          <i class="arr down"></i>
        </li>
        <li class="trigger sales-seq">
          销量
          <i class="arr down"></i>
        </li>
        <li class="filter-handle">
          筛选
          <div id="filter_container" style="display:none;">
            <{include file='wap/gallery/screen.html'}>
          </div>
        </li>
      </ul>
      <ul class="panel-list" style="    padding-top: 1.8rem;">
        <li class="panel act"><{include file='wap/gallery/type/list.html'}></li>
        <li class="panel"></li>
        <li class="panel"></li>
        <li class="panel"></li>
      </ul>
    </div>
  </div>

    <section class="m-input">
        <input type="hidden" value="" id="product_id">
        <input type="hidden" value="" id="old_num">
        <p class="u-title">输入订购数量</p>
        <p class="u-info">
            <span><span id="u-min"></span><span></span>件起订</span>
            <span>规格：<span id="u-size"></span></span>
            <span>单位：<span id="u-unit"></span></span>
        </p>
        <div>
            <input type="number" name="goods[num]" id="new_input" autofocus>
        </div>
        <div class="m-btn">
            <div class="u-btn u-cancle">取消</div>
            <div class="u-btn u-submit">确定</div>
        </div>
    </section>
    <section class="u-cover"></section>
</div>
<script>
(function(){
  var container = document.body;
  var priceSeq = 'price desc';
  var salesSeq = 'buy_w_count desc';
  var url = '<{link app=b2c ctl=wap_gallery act=ajax_get_goods}>';
  var page = '1';
  var cat_id = '<{$screen.cat_id}>';
  var scontent=location.search;

    if(scontent.indexOf("?scontent") == 0 ){
        scontent=scontent.substr(1);
    }
    else{
        scontent=null;
    }

    var filter_dialog;
    /*html5 history manage*/
  setTimeout(function(){
      window.history.replaceState({url: location.href, html: container.innerHTML}, null, location.href);
  }, 0);

  window.onpopstate = function(event){
      var data;
      if(event && event.state){
          data = event.state;
      }else{
          data = {html: container.innerHTML, url: location.href};
      }

      var scripts = '';
      var text = data.html.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
          scripts += code + '\n';
          return '';
      });
      container.innerHTML = text;

      var script = document.createElement('script');
      script.text = scripts;
      document.body.appendChild(script);
      // document.head.removeChild(script);
  };

  if(sessionStorage.params_single&&sessionStorage.params_single!=""){
      filterGoods($('.trigger-list .act'));
  }

  function filterGoods(t,e,status){
    var orderby = 'orderBy=',
        p = 'page=',
        sear = '',
        search = location.search,
        virtual_cat_id="<{$virtual_cat_id}>";

    if(e&&$('.trigger-list .act').hasClass('price-seq')) orderby += priceSeq;
    else if(e&&$('.trigger-list .act').hasClass('sales-seq')) orderby += salesSeq;
    else if(t.hasClass('price-seq')){
        orderby += priceSeq;
    }
    else if(t.hasClass('sales-seq')){
        orderby += salesSeq;
    }
    if(e&&e.num){
        p += e.num;
        page = e.num;
    }

    if(sessionStorage.params_single && !status){
        console.log("使用缓存");
        var params = search.substr(1);
        if(virtual_cat_id!=''){
            params+="&virtual_cat_id="+virtual_cat_id;
        }
    }
    else{
        console.log("使用点击");
        var params = ['showtype=list', p, encodeURI(orderby), sear, $('#J_filter form').serialize()].filter(function(d){
            return d;
        }).join('&');
        if(virtual_cat_id!=''){
            params+="&virtual_cat_id="+virtual_cat_id;
        }
    }
    if(scontent){
        params+="&"+scontent;
        console.log("用了")
    }
    $.post(url, params, function(re){
        $(".panel-list").html(re);

        var reg = location.search?location.search:location.href;
        window.history.pushState({url: location.href, html: container.innerHTML}, null, location.href.replace(reg, '?' + params));
        sessionStorage.params_single=params;
    });
  }

  $('.J-tab .trigger').on('touchend',function(e){e.preventDefault();}).on('tap',function(){
    page = 1;
    $(this).siblings("li").removeClass("act");
    $(this).addClass(("act"));

    if( $(this).hasClass('sales-seq') ){
        salesSeq = salesSeq == 'buy_w_count desc' ? 'buy_w_count asc' : 'buy_w_count desc';
        console.log(salesSeq);
        if(salesSeq == 'buy_w_count asc'){
            $(this).find('i')[0].className = 'arr down';
        }else{
            $(this).find('i')[0].className = 'arr top';
        }
    }
    else if ($(this).hasClass('price-seq')) {
        if(priceSeq == 'price desc'){

            priceSeq = 'price asc';
            $(this).find('i')[0].className = 'arr down';
        }else{
            priceSeq = 'price desc';
            $(this).find('i')[0].className = 'arr top';
        }
    }

    filterGoods($(this),null,1);
  });

  $('.filter-handle').on('tap',function(){
    page = 1;
    filter_dialog = new Dialog('#filter_container',{'type':'confirm'});
  });

  $('.panel-list').on('click',function(e){
    var t = $(e.target);
    if(t.hasClass('flip')){
        t.num=parseInt($("option.flip[selected='selected']").attr("page"));
      if(t.hasClass('next'))t.num++;
      if(t.hasClass('prev'))t.num--;
      filterGoods($('.trigger-list .act'),t,1);
        $(window).scrollTop(0);
      return false;
    }
  }).on('change','select',function(){
    var t = $(this.options[this.selectedIndex]);
    if(t.hasClass('flip')){
      t.num = parseInt(t.attr('page'));
      filterGoods($('.trigger-list .act'),t,1);
        $(window).scrollTop(0);
    }
  });
  $('#J_filter').on('touchend',function(e){e.preventDefault();}).on('tap',function(event){
    var _this = this,
    t = $(event.target),
    tag = t[0].tagName.toLowerCase(),
    table = t.parents('table');
    switch(tag){
      case 'dt':
        if( t.hasClass('handle') ){
          t.removeClass('handle').next().addClass('hide');
        }else{
          t.addClass('handle').next().removeClass('hide');
          t.siblings('.handle').removeClass('handle').next().addClass('hide');
        }
        break;
      case 'td':
        if(t.hasClass('empty'))return;
        table.find('td').removeClass('handle');
        t.addClass('handle');
        table.parent().prev().find('span').html(t.html());
        var fid = t.attr('data-fid');
        if(fid&&fid.length){
          fid = fid.split('-');
          table.prev().attr({name:fid[0]+'[]',value:fid[1]});
          table.parent().prev().find('span').addClass('act');
        }else{
          var hide = table.prev();
          if(/^cat_id/.test(hide.attr('name'))) {
              hide.val(cat_id);
          }
          else {
              hide.val('');
          }
          table.parent().prev().find('span').removeClass('act');
        }
        break;
      case 'span':
        if(t.hasClass('reset')){
          $.each($(this).find('table'),function(){
            $(this).find('td').eq(0).trigger('tap');
          });
        }
        break;
      case 'input':
        filterGoods( $('.trigger-list .act'),t );
        filter_dialog.close();
        break;
    }
  });

  $('#J_search').on('tap',function(){
    var prt = $(this).parent(),
    bar = prt.parents('.a-bar');
    if(prt.find(".a-search-ipt").val()==""){
        alert("请输入搜索内容");
        return;
    }
    else{
        prt.submit();
    }

  });
  $('#J_search_pt').unbind("submit").on("submit",function (e) {
      if($("input.a-search-ipt").val()==""){
          alert("请输入搜索内容");
          e.preventDefault();
      }
  });


    //关闭输入框
    $(".u-cover,.u-cancle").on("click",function () {
        $(".m-input").hide();
        $(".u-cover").hide();
        $("#u-min").html("");
        $("#u-size").html("");
        $("#u-unit").html("");
    });
    //输入框提交
    $("#new_input").on("focus",function () {
        console.log("获取焦点");
    });
    $(".m-input .u-submit").on("click",function () {
        var min=parseInt($("#u-min").text());
        var input=parseInt($(this).parents(".m-input").find("input[type='number']").val()) ;
        var _id=parseInt($(this).parents(".m-input").find("#product_id").val());
        var old_num=parseInt($(this).parents(".m-input").find("#old_num").val());
        var $parents=$("div[data-href='"+_id+"']").parents("li");
        if(!input){
            alert("请输入购买数量");
        }
        else if(input%min!=0){
            alert("请输入以"+min+"为倍数的数量");
        }
        else{
            console.log($parents);

            $.post("<{link app=b2c ctl=wap_cart act=entry arg0='goods'  arg1='"+_id+"' arg2='"+input+" ' }>",function (re) {
                re=JSON.parse(re);
                if(re.success){
                    alert("加入购物车成功");
                    location.reload();
                }
                else{
                    alert(re.error);
                }
                $(".m-input,.u-cover").hide();
            })
        }
    })
})();


//弹出输入框
function showInput(a) {
    var $this=$(a).parents("li");
    var min_buy=$this.find(".u-min_buy").val();
    var good_standard=$this.find(".good_standard").val();
    var unit=$this.find(".u-unit").val();
    var num=parseInt($this.find(".u-num").text());
    var id=$this.find(".pt-h-link").attr("data-href");
    $("#product_id").val(id);
    $("#u-min").html(min_buy);
    $("#u-size").html(good_standard);
    $("#u-unit").html(unit);
    $(".m-input").show();
    $(".u-cover").css("display","block");
    $("#new_input,#old_num").val(num);

}

//    添加商品入购物车
function addCart(a) {
    //判断登录跳转
    var e = $.fn.cookie('UNAME')?$.fn.cookie('UNAME'):'';
    console.log(e);
    if(!e){
        location.href="passport.html";
        return false;
    }
    var $this=$(a);
    var id=$this.parents(".pt-h-link").attr("data-href");
    var num=$this.siblings(".u-num").text();
    var add_href='<{link app=b2c ctl=wap_cart act=addCart arg0=goods arg1="'+id+'"}>?';
    var dec_href='<{link app=b2c ctl=wap_cart act=decCart arg0=goods arg1="'+id+'"}>?';
    console.log(add_href);
    if($this.hasClass("u-add")){
        $.post(add_href,function (re) {
            try{
                re=JSON.parse(re);
                if(re.success){
                    $this.parents(".u-product").find(".u-num").html(re.success);
                    add_frame($this);
                }
                if(re.error){
                    alert("库存不足，加入购物车失败");
                }
            }
            catch (e){}
        })
    }
    else{
        $.post(dec_href,function (re) {
            try{
                if(num==0||num<0){
                    return false;
                }
                re=JSON.parse(re);
                if(re.success){
                    $this.parents(".u-product").find(".u-num").html(re.success);
                }

            }
            catch (e){}
        })
    }
}

//    加入购物车动画
function add_frame(a) {
    var $this=a.parents(".u-product").find("img");
    var old_top=$this.offset().top;
    var old_left=$this.offset().left;
    var _width=$this.width();
    var _height=$this.height();
    var $new_img=$this.clone();
    var scroll=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
    console.log("高度1为"+old_top);
    console.log(document.documentElement.scrollTop);
    if(old_top>scroll){
        old_top-=scroll;
        console.log("高度2为"+old_top);
    }
    $new_img.css({
        "position":"fixed",
        "width":_width,
        "height":_height,
        "left": old_left,
        "top": old_top,
        "z-index":"22222",
        "border-radius":"2rem"
    });
    $("body").append($new_img);

    $new_img.animate({
        "width":".5rem",
        "height":".5rem",
        "top":"11.8rem",
        "left":"4.2rem"

    },500,"swing");

    setTimeout(function () {
        $new_img.remove();
    },505);

}
</script>
